<template>
  <div style="margin: 30px;">
    <el-card class="box-card" style="width:800px;">
        <div slot="header" class="clearfix">
          <el-page-header @back="goback" content="商品详情">
          </el-page-header>
        </div>
        <el-form :model="form" ref="form" :rules="rules" label-width="100px" status-icon style="margin:20px;">
        <el-form-item
        prop="num"
        label="商品编号"
        style="width:400px;"
        >
          <el-input v-model="form.num" :disabled="this.type==='edit'?true:false"></el-input>
        </el-form-item>
        <el-form-item
        prop="name"
        label="商品名称"
        style="width:400px;"
        >
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item
        prop="cate_id"
        label="所属分类">
          <el-cascader 
            :options="options"
            clearable
            @change="getCheckedNodes"></el-cascader>
        </el-form-item>
        <el-form-item
        prop="price"
        label="商品单价"
        >
        <el-input-number v-model="form.price" :precision="2" :step="0.1" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item
        prop="sum"
        label="商品数量"
        >
        <el-input-number v-model="form.sum" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item
        prop="details"
        style="width:700px;"
        label="商品描述">
        <el-input  type="textarea" :autosize="{ minRows: 5, maxRows: 8}" v-model="form.details"></el-input>
        </el-form-item>
        <el-form-item style="margin-bottom: 50px;">
          <el-button type="primary" @click="submitForm('form')">{{ this.type==='edit'?'更新':'添加' }}</el-button>
          <el-button @click="resetForm('form')" :disabled="this.type==='edit'?true:false">{{ this.type==='edit'?'取消':'清空' }}</el-button>
        </el-form-item>
      </el-form>
      </el-card>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { setnewgood, updategood }from '@/api/index'
export default {
    name:'add',
    data(){
      var validatenum = (rule, value, callback) => {
      var numtype = /^[0-9]+.?[0-9]*/
      if (!numtype.test(value)) {
          return callback(new Error('请输入数字值'));
      }else{
        callback();
      }
    }
    var validatename = (rule, value, callback) => {
      if(!value) return callback(new Error('商品名称不能为空'));
      else callback();
    }
    var validatenotzero = (rule, value, callback) => {
      if(value === 0.00||value === 0) return callback(new Error('请输入一个非零的值'));
      else callback();
    }
      return {
        form:{
          num:'',
          name:'',
          cate_id:'',
          price:0.00,
          sum:0,
          details:''
        },
        rules:{
          num:[{ required: true, validator: validatenum, trigger: 'blur' }],
          name:[{ required: true, validator: validatename, trigger: 'blur' }],
          price:[{ required: true, validator: validatenotzero, trigger: 'change' }],
          sum:[{ required: true, validator: validatenotzero, trigger: 'change' }]
        },
        options: [{
          value: '1',
          label: '水果',
        },{
          value: '2',
          label: '蔬菜',
        },{
          value: '3',
          label: '水产',
        },{
          value: '4',
          label: '豆类',
        },{
          value: '5',
          label: '粉类',
        },{
          value: '6',
          label: '米类',
        },{
          value: '9',
          label: 'ceshi',
        }],
      }
    },
    computed:{
      ...mapState('add',['goodsrowdata','type'])
    },
    methods:{
      getCheckedNodes(e){
        this.form.cate_id = e[0]
        console.log(this.form.cate_id)
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if(this.type!=='edit')
              setnewgood(this.form).then(req => {
                if(req.data.status === 400)
                  this.$notify({
                    title: '警告',
                    message: req.data.msg,
                    type: 'warning',
                    duration: 2500
                  });
                else if(req.data.status === 500)
                  this.$notify.error({
                    title: '错误',
                    message: req.data.msg,
                    duration: 2500
                  });
                else {
                  this.$notify({
                    title: '成功',
                    message: req.data.msg,
                    type: 'success',
                    duration: 2500
                  });
                  this.$confirm('商品添加成功，是否立即返回到商品详情页面?', '提示', {
                    confirmButtonText: '立即返回',
                    cancelButtonText: '稍后返回',
                    type: 'success'
                    }).then(() => {
                      this.$router.push('goods')
                      this.$message({
                        message: '已返回',
                        type: 'success'
                      });
                    }).catch(() => {
                      this.$message({
                        type: 'warning',
                        message: '已取消'
                      });          
                    });
                }
              }).catch(err => console.log(err))
              else {
                updategood(this.form).then(req => {
                  if(req.data.status === 400)
                  this.$notify({
                    title: '警告',
                    message: req.data.msg,
                    type: 'warning',
                    duration: 2500
                  });
                else if(req.data.status === 500)
                  this.$notify.error({
                    title: '错误',
                    message: req.data.msg,
                    duration: 2500
                  });
                else {
                  this.$notify({
                    title: '成功',
                    message: req.data.msg,
                    type: 'success',
                    duration: 2500
                  });
                }}).catch(err => console.log(err))
              }
          } else {
            this.$notify({
              title: '警告',
              message: '请按照表单验证规则输入数据！',
              type: 'warning',
              duration: 2500
            });
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].validate((valid) => {
        if(this.type!=='edit')
          if (valid) {
            this.$confirm('注意！此操作将清空所有输入,是否确认?', '提示', {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.$refs[formName].resetFields();
              this.$message({
                message: '已重置',
                type: 'success'
              });
            }).catch(() => {
              this.$message({
                type: 'warning',
                message: '已取消'
              });          
            });
          }else {
            this.$refs[formName].resetFields();
            this.$message('已重置');
          }
        else {

        }
        })
      },
      goback(){
        this.$confirm('是否确认返回商品页面?如有数据输入则不会保存', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$router.push('goods')
          this.$message({
            message: '已返回',
            type: 'success'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        });
      }
    },
    mounted(){
      if(this.type==='edit')  this.form = this.goodsrowdata
    }
}
</script>

<style>

</style>